package com.lz.frame.domain.service.impl;

import java.util.*;
import java.util.stream.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lz.frame.domain.VO.UserVO;
import com.lz.frame.domain.entity.*;
import com.lz.frame.domain.mapper.*;
import com.lz.frame.domain.service.UserLoginService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserLoginServiceImpl implements UserLoginService {


    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserVO getUserByUserId(User user) {
        UserVO userVO = new UserVO();
        userVO.setUser(user);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, user.getId());
        wrapper.select(UserRole::getRoleId);
        List<UserRole> userRoles = userRoleMapper.selectList(wrapper);
        List<String> collect = userRoles.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());
        List<Role> roles = roleMapper.selectBatchIds(collect);
        userVO.setRoles(roles);
        LambdaQueryWrapper<RoleMenu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(RoleMenu::getRoleId, collect);
        List<RoleMenu> roleMenus = roleMenuMapper.selectList(wrapper1);
        List<String> menus = roleMenus.stream().map(roleMenu -> roleMenu.getMenuId()).collect(Collectors.toList());
        List<Menu> menus1 = menuMapper.selectBatchIds(menus);
        userVO.setMenus(menus1);
        return userVO;
    }

    @Override
    public boolean register(String username, String password) {
        String encode = passwordEncoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(encode);
        if (userMapper.insert(user) > 0) {
            return true;
        }
        return false;
    }
}
